/**
 * 删除重复的通用头盔脚本
 * 删除与职业头盔重复的通用头盔
 */

const mysql = require('mysql2/promise');
require('dotenv').config({ path: './nestjs-app/.env' });

class DuplicateHelmetRemover {
  constructor() {
    this.connection = null;
  }

  async connect() {
    try {
      this.connection = await mysql.createConnection({
        host: process.env.DB_HOST || '43.143.253.188',
        port: process.env.DB_PORT || 3306,
        user: process.env.DB_USER || 'nextjs',
        password: process.env.DB_PASS || 'yEAiRE2jcxTyRBy5',
        database: process.env.DB_NAME || 'nextjs',
        timezone: '+08:00'
      });
      console.log('✅ 数据库连接成功');
    } catch (error) {
      console.error('❌ 数据库连接失败:', error.message);
      throw error;
    }
  }

  async disconnect() {
    if (this.connection) {
      await this.connection.end();
      console.log('🔌 数据库连接已关闭');
    }
  }

  /**
   * 删除重复的通用头盔
   */
  async removeDuplicateHelmets() {
    try {
      console.log('🔄 删除重复的通用头盔...');

      // 需要删除的重复通用头盔
      const duplicateHelmets = [
        { id: 162, name: '布帽', reason: '与布帽·武重复' },
        { id: 163, name: '方士帽', reason: '与布帽·文重复' },
        { id: 164, name: '貂皮帽', reason: '与皮帽·异重复' }
      ];

      console.log(`📊 准备删除 ${duplicateHelmets.length} 个重复的通用头盔`);

      for (const helmet of duplicateHelmets) {
        // 检查头盔是否存在
        const [existing] = await this.connection.execute(
          'SELECT id, name, type, base, level FROM equipment_base WHERE id = ?',
          [helmet.id]
        );

        if (existing.length > 0) {
          const helmetData = existing[0];
          console.log(`📝 删除头盔 ${helmet.id} (${helmet.name}): ${helmet.reason}`);
          console.log(`   类型=${helmetData.type}, 基础=${helmetData.base}, 等级=${helmetData.level}`);

          // 删除头盔
          await this.connection.execute(
            'DELETE FROM equipment_base WHERE id = ?',
            [helmet.id]
          );

          console.log(`✅ 头盔 ${helmet.id} (${helmet.name}) 删除成功`);
        } else {
          console.log(`⚠️  头盔 ${helmet.id} (${helmet.name}) 不存在，跳过`);
        }
      }

      console.log('✅ 重复通用头盔删除完成！');

    } catch (error) {
      console.error('❌ 删除重复头盔失败:', error.message);
      throw error;
    }
  }

  /**
   * 验证删除结果
   */
  async verifyDeletion() {
    try {
      console.log('\n🔍 验证删除结果...');

      // 检查头盔基础类型分布
      const [baseStats] = await this.connection.execute(`
        SELECT base, COUNT(*) as count
        FROM equipment_base 
        WHERE type = 1
        GROUP BY base 
        ORDER BY base
      `);

      console.log('📊 删除后的头盔基础类型分布:');
      baseStats.forEach(stat => {
        const baseName = this.getBaseName(stat.base);
        console.log(`  基础类型 ${stat.base} (${baseName}): ${stat.count} 个头盔`);
      });

      // 检查各职业头盔列表
      console.log('\n📋 各职业头盔列表:');
      for (let base = 1; base <= 3; base++) {
        const [helmets] = await this.connection.execute(`
          SELECT id, name, level 
          FROM equipment_base 
          WHERE type = 1 AND base = ?
          ORDER BY level, id
        `, [base]);

        const baseName = this.getBaseName(base);
        console.log(`\n  基础类型 ${base} (${baseName}): ${helmets.length} 个头盔`);
        helmets.forEach(helmet => {
          console.log(`    ID=${helmet.id}, 名称=${helmet.name}, 等级=${helmet.level}`);
        });
      }

      // 检查是否还有通用头盔
      const [genericHelmets] = await this.connection.execute(`
        SELECT id, name, base, level
        FROM equipment_base 
        WHERE type = 1 AND name NOT LIKE '%·武' AND name NOT LIKE '%·文' AND name NOT LIKE '%·异'
        ORDER BY id
      `);

      if (genericHelmets.length > 0) {
        console.log(`\n⚠️  仍有 ${genericHelmets.length} 个通用头盔:`);
        genericHelmets.forEach(helmet => {
          const baseName = this.getBaseName(helmet.base);
          console.log(`    ID=${helmet.id}, 名称=${helmet.name}, 基础=${helmet.base}(${baseName}), 等级=${helmet.level}`);
        });
      } else {
        console.log('\n✅ 所有通用头盔已删除，只保留职业头盔');
      }

    } catch (error) {
      console.error('❌ 验证删除结果失败:', error.message);
      throw error;
    }
  }

  /**
   * 获取基础类型名称
   */
  getBaseName(base) {
    const baseNames = {
      1: '武士',
      2: '文人',
      3: '异师'
    };
    return baseNames[base] || '未知';
  }

  /**
   * 运行完整的删除流程
   */
  async run() {
    try {
      await this.connect();
      await this.removeDuplicateHelmets();
      await this.verifyDeletion();
      
      console.log('\n🎉 重复头盔删除完成！');
      
    } catch (error) {
      console.error('💥 删除流程失败:', error.message);
      process.exit(1);
    } finally {
      await this.disconnect();
    }
  }
}

// 运行删除脚本
async function main() {
  const remover = new DuplicateHelmetRemover();
  await remover.run();
}

// 如果直接运行此脚本
if (require.main === module) {
  main().catch((error) => {
    console.error('💥 脚本执行失败:', error.message);
    process.exit(1);
  });
}

module.exports = DuplicateHelmetRemover;
